import {ref} from 'vue';
import store from '@/store';
import {defineStore} from 'pinia';
import {type RouteRecordRaw} from 'vue-router';
import {constantRoutes, asyncRoutes} from '@/router';

import asyncRouteSettings from '@/config/async-route';

const hasPermission = (roles: string[], route: RouteRecordRaw) => {
    const routeRoles = route.meta?.roles;
    return routeRoles ? roles.some((role) => routeRoles.includes(role)) : true;
};

const filterAsyncRoutes = (routes: RouteRecordRaw[], roles: string[]) => {
    const res: RouteRecordRaw[] = [];
    routes.forEach((route) => {
        const tempRoute = {...route};
        if (hasPermission(roles, tempRoute)) {
            if (tempRoute.children) {
                tempRoute.children = filterAsyncRoutes(tempRoute.children, roles);
            }
            res.push(tempRoute);
        }
    });
    console.log('🚀 ~ file: permission.ts:25 ~ filterAsyncRoutes ~ res:', res);
    return res;
};

export const usePermissionStore = defineStore('permission', () => {
    const routes = ref<RouteRecordRaw[]>([]);
    const dynamicRoutes = ref<RouteRecordRaw[]>([]);

    const setRoutes = (roles: string[]) => {
        const accessedRoutes = asyncRouteSettings.open ? filterAsyncRoutes(asyncRoutes, roles) : asyncRoutes;
        routes.value = constantRoutes.concat(accessedRoutes);
        dynamicRoutes.value = accessedRoutes;
    };
    // todo 固定的数据,后期更换
    routes.value = constantRoutes;
    console.log('🚀 ~ file: permission.ts:6 ~ constantRoutes:', routes);

    return {routes, dynamicRoutes, setRoutes};
});

/** 在 setup 外使用 */
export function usePermissionStoreHook() {
    return usePermissionStore(store);
}
